package org.mca.mcaweb.interceptor;

import i18n.MsgUtil;

import java.io.Serializable;
import java.util.ResourceBundle;

import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import javax.persistence.EntityManager;

import org.mca.mcaweb.annotation.Transactional;
import org.mca.mcaweb.util.ResourceBundleUtil;

@Interceptor
@Transactional
public class TransactionInterceptor implements Serializable {

	private static final long serialVersionUID = 9185796696742388134L;
	
	private ResourceBundle bundle = ResourceBundleUtil.getResourceBunde();

	@Inject
	private EntityManager em;
	
	@AroundInvoke
	public Object intercept(InvocationContext ctx) throws Exception {
		
		Object resultado = null;
		
		try {
			
			em.getTransaction().begin();
			resultado = ctx.proceed();
			em.getTransaction().commit();
			
		} catch (Exception e) {
			e.printStackTrace();
			if (e.getCause().getMessage().startsWith("org.hibernate.exception.ConstraintViolationException")) {
				MsgUtil.addErrorMessage("Interceptador",bundle.getString("label.error.deleteDescription"));
			} else if (e.getCause().getMessage().startsWith("org.hibernate.exception.DataException")) {
				MsgUtil.addErrorMessage("Interceptador",bundle.getString("label.registro.erro.dados.incompativeis"));
			} else if (e.getCause().getMessage().startsWith("org.hibernate.exception.GenericJDBCException")) {
				MsgUtil.addErrorMessage("Interceptador",bundle.getString("label.registro.erro.desconhecido"));
			} else if (e.getCause().getMessage().startsWith("org.hibernate.exception.JDBCConnectionException")) {
				MsgUtil.addErrorMessage("Interceptador",bundle.getString("label.registro.erro.comunicar.banco"));
			} else if (e.getCause().getMessage().startsWith("org.hibernate.exception.LockAcquisitionException")) {
				MsgUtil.addErrorMessage("Interceptador",bundle.getString("label.registro.erro.desconhecido"));
			} else if (e.getCause().getMessage().startsWith("org.hibernate.exception.NestableException")) {
				MsgUtil.addErrorMessage("Interceptador",bundle.getString("label.registro.erro.desconhecido"));
			} else if (e.getCause().getMessage().startsWith("org.hibernate.exception.NestableRuntimeException")) {
				MsgUtil.addErrorMessage("Interceptador",bundle.getString("label.registro.erro.desconhecido"));
			} else if (e.getCause().getMessage().startsWith("org.hibernate.exception.SQLGrammarException")) {
				MsgUtil.addErrorMessage("Interceptador",bundle.getString("label.registro.erro.sql"));
			} else if(e.getCause().getMessage().startsWith("could not insert")){
				MsgUtil.addErrorMessage("Interceptador",bundle.getString("label.registro.erro.could.not.insert"));
			} else {
				MsgUtil.addErrorMessage("Interceptador",bundle.getString("label.registro.erro.desconhecido"));
			}
			em.getTransaction().rollback();
		} 
		
		return resultado;
	}
}
